const gulp = require('gulp');
const path = require('path');
const fs = require('fs');
const browserSync = require('browser-sync');
const globalLoadPlugin = require('gulp-load-plugins');
const frontMatter = require('gulp-front-matter');
const del = require('del');
const runSequence = require('run-sequence');
const cleanCSS = require('gulp-clean-css');
const sourcemaps = require('gulp-sourcemaps');

const $ = globalLoadPlugin();
const reload = browserSync.reload;


const THEME_NAME = 'b-elegant';
const ROOT = path.resolve(`${__dirname}`,'../../../');
const THEME_ROOT = `${ROOT}/dist/themes/`;




const pathVars = {
	LIBS:`${ROOT}/node_modules`
	
}
const eslintConfig ={
	rules:{
        "camelcase": 1,
        "comma-dangle": 2,
        "quotes": 0,
        //"no-multiple-empty-lines": [0, {"max": 100}],
        //"no-mixed-spaces-and-tabs": [0],
    },
	globals: [
        'jQuery',
        '$',
        'Swiper'
    ],
    envs: [
        'browser'
    ]
}

//lib assets
const ASSETS_LIST = {
	css: {
			swiper: "swiper/dist/css/swiper.css",
			animatelo: "animate.css/animate.css",
			//fontAwesome:"Font-Awesome/css/font-awesome.css"
			//fullpage:"fullpage.js/dist/jquery.fullpage.css",
		},
	js: {
			jquery:'jquery/dist/jquery.js',
			swiper:"swiper/dist/js/swiper.jquery.js",
			qrcode:"jquery-qrcode/dist/jquery-qrcode.js"

		},
	fonts:{
		//fontAwesome:"Font-Awesome/fonts/**.*"
	}

};

gulp.task('theme_cn',cb=>{
	const AUTOPREFIXER_BROWSERS = [
	    'ie >= 10',
	    'ie_mob >= 10',
	    'ff >= 30',
	    'chrome >= 34',
	    'safari >= 7',
	    'opera >= 23',
	    'ios >= 7',
	    'android >= 4.4',
	    'bb >= 10'
	];

	return gulp.src('scss/theme_cn.scss')
		.pipe($.scss({precision: 10}).on('error', $.sass.logError))
	    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
	    .pipe($.size({title: 'styles'}))
	    .pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/css`));
});



gulp.task('dev:script',cb=>{
	gulp.src('script/index.js')
		//.pipe($.rename('index.min.js'))
	    //.pipe($.eslint(eslintConfig))
	    //.pipe($.eslint.format())
		//.pipe($.eslint.failAfterError())
		//.pipe($.sourcemaps.init())
		.pipe($.babel())
		//.pipe($.uglify())
		//.pipe($.sourcemaps.write('./'))
		//.pipe($.rename(prefix: "_"))
	   .pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/js`));
	
	
});

gulp.task('dev:scss',cb=>{
	const AUTOPREFIXER_BROWSERS = [
	    'ie >= 10',
	    'ie_mob >= 10',
	    'ff >= 30',
	    'chrome >= 34',
	    'safari >= 7',
	    'opera >= 23',
	    'ios >= 7',
	    'android >= 4.4',
	    'bb >= 10'
	];

	return gulp.src('scss/theme.scss')
		//.pipe($.rename('theme.min.css'))
		.pipe($.sourcemaps.init())
	    .pipe($.scss({precision: 10}).on('error', $.sass.logError))
	    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
	    .pipe(cleanCSS())
	    .pipe($.size({title: 'styles'}))
	    .pipe($.sourcemaps.write('./'))
	    .pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/css`));
});

gulp.task('svg',cb=>{
	return gulp.src('images/*.svg')
	    .pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/images`));
});
gulp.task('images',cb=>{
	return gulp.src(['images/*.png'])
	    .pipe($.cache($.imagemin({
		    progressive: true,
		    interlaced: true
		})))
		.pipe($.size({title: 'images'}))
		.pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/images`));
});

gulp.task('dev',['dev:script','dev:scss','compile:tpl'], cb=>{

});

gulp.task('build',cb=>{

});
gulp.task('default',cb=>{
	let dist_path = path.resolve(THEME_ROOT,THEME_NAME);
	console.log(dist_path);
});


gulp.task('compile:tpl',[],cb=>{
	//let sources = gulp.src([`${THEME_ROOT}/${THEME_NAME}/js/*.js`, `${THEME_ROOT}/${THEME_NAME}/css/*.css`], {read: false});


	let result = gulp.src('template/index.html')
	    .pipe($.data(()=>{
	    	return JSON.parse(fs.readFileSync('data/data.json'))
	    }))
	    .pipe($.swig())
	    //.pipe($.inject(sources,{relative:true,removeTags:true/*,addRootSlash:false,addPrefix:'..'*/}))
	    .pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}`));

	return result;
});


// lib assets
gulp.task('copy:lib',cb=>{
	runSequence('clean:lib-dist',['copy:lib-css','copy:lib-script','copy:lib-fonts'],cb);
});

gulp.task('copy:lib-css',[],cb=>{
	return gulp.src('lib/css/*.css')
		.pipe(sourcemaps.init())
		.pipe($.concat('all.min.css'))
		.pipe(cleanCSS({debug: true}, function(details) {
      		//console.log(details.name + ': ' + details.stats.originalSize);
      		//console.log(details.name + ': ' + details.stats.minifiedSize);
    	}))
    	.pipe($.size({title:'style'}))
		.pipe(sourcemaps.write('./'))
		.pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/css`));
})

gulp.task('copy:lib-jquery',cb=>{
	return gulp.src('lib/js/jquery.js')
		.pipe($.rename('jquery.min.js'))
		.pipe(sourcemaps.init())
		.pipe($.uglify())
		.pipe($.size({title:'jquery'}))
		.pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/js`));
});
gulp.task('copy:lib-script',['copy:lib-jquery'],cb=>{
	
	return gulp.src(['lib/js/*.js','!lib/js/jquery.js'])
		.pipe(sourcemaps.init())
		.pipe($.concat('bundle.min.js'))
		.pipe($.uglify())
		.pipe($.size({title:'script'}))
		.pipe(sourcemaps.write('./'))
		.pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/js`));
});
gulp.task('copy:lib-fonts',cb=>{
	return gulp.src('lib/fonts/*')
		.pipe($.size({title:'fonts'}))
		.pipe(gulp.dest(`${THEME_ROOT}/${THEME_NAME}/fonts`));
})
gulp.task('clean:lib-dist',cb=>{
	return del([`${THEME_ROOT}/${THEME_NAME}/fonts`,`${THEME_ROOT}/${THEME_NAME}/js`,`${THEME_ROOT}/${THEME_NAME}/css`],{force:true})
	    .then(paths=>{
	    	console.log('Deleted files and folders:\n======================', paths.join('\n======================'));
	    })
});



// prepare assets
gulp.task('prepare',['clean:lib'],cb=>{
    let result;

	for(let key in ASSETS_LIST){
		let list = Object.values(ASSETS_LIST[key]).map((item)=>{
			return path.resolve(pathVars.LIBS,item);
		});
		//let condition = key!=='fonts';

		new Promise(
			(resolve,reject)=>{
				result =  gulp.src(list)
				//.pipe($.if(condition,$.rename({prefix: "_"})))
				.pipe(gulp.dest(`lib/${key}`));

				cb();
				//return result;
				function cb(){
					resolve(`assets:[ ${key} ] is completed prepared!`);
				}
			}
		).then((msg)=>{
			console.log(msg);
			//return result;
		}); 

	};

	cb = function(){
		console.info('PREPARE-ASSETS:===================================prepare-assets===================================');
	}

	cb();

	//return stream for run-sequence useing
	return result;
	
});


gulp.task('clean:lib',cb=>{
	let result =  del('lib');

	cb = ()=>{
	   console.info('CLEAR::===================================clear dist===================================');
	}

	cb();
	return result;
});


gulp.task('server',cb=>{
	browserSync({
	    notify: false,
	    // Customize the Browsersync console logging prefix
    	logPrefix: 'CARD',
    	// Allow scroll syncing across breakpoints
    	//scrollElementMapping: ['main', '.mdl-layout'],
    	server:`${THEME_ROOT}/${THEME_NAME}`,
    	port: 3000
	});

	gulp.watch('template/index.html', ['dev',reload]);
    //gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
    //gulp.watch(['app/scripts/**/*.js'], ['lint', 'scripts', reload]);
    //gulp.watch(['app/images/**/*'], reload);
});